<template></template>
<script setup lang="ts">
  import { useStore } from '@/store'
  import { useRouter, useRoute } from 'vue-router'
  import { onMounted } from 'vue'
  import { decode } from 'js-base64'
  import { isSaaS } from '@/utils/is'
  import { object2param } from '@/utils/index'

  const store = useStore()
  const router = useRouter()
  const route = useRoute()

  console.log('route', route.query)
  const path = JSON.parse(decodeURIComponent(route.query?.path))
  console.log(object2param(path))
  // 订阅消息场景获取
  const params = object2param(path)
  console.log(urlParamsToObject(params))
  // const reductTo = params.split('?')[0]
  // console.log(reductTo)

  const {
    query: { code, token, storeId, redirect, accountCode, accountName }
  } = route

  onMounted(() => {
    handleLogin()
  })

  function urlParamsToObject(url) {
    const search = url.split('?')[1]
    const searchParams = new URLSearchParams(search)
    const params = {}
    for (const [key, value] of searchParams) {
      params[key] = value
    }
    return params
  }

  async function handleLogin() {
    const { data } = await store.dispatch('user/delegateLogin', {
      path: decodeURIComponent(route.query?.path)
    })
    const { VITE_BMS_HOSTNAME } = import.meta.env
    // 打开BMS系统
    let origin
    if (import.meta.env.MODE === 'production') {
      origin = `https://${data.storeId}-${VITE_BMS_HOSTNAME}`
    } else if (import.meta.env.MODE === 'staging') {
      if (VITE_BMS_HOSTNAME === 'testbms.itaored.com') {
        origin = `https://${data.storeId}-${VITE_BMS_HOSTNAME}`
      } else {
        origin = `https://${data.storeId}-test${VITE_BMS_HOSTNAME}`
      }
    } else {
      origin = 'http://localhost:9001'
    }
    window.location.href = `${origin}/delegate?code=${data.code}&imLoginUrl=${path?.url}`
  }
</script>
